package ro.gateway.aida.rss;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.obj.Activity;
import ro.gateway.aida.obj.Organization;
import ro.gateway.aida.obj.db.ActivityDB;
import ro.gateway.aida.obj.db.OrganizationDB;
import ro.gateway.aida.servlet.Constants;
import ro.gateway.aida.usr.UserDB;
import viecili.jrss.generator.RSSFeedGenerator;
import viecili.jrss.generator.RSSFeedGeneratorImpl;
import viecili.jrss.generator.elem.Channel;
import viecili.jrss.generator.elem.Item;
import viecili.jrss.generator.elem.RSS;

/*
 * Created on Mar 6, 2005
 *
 * Author: Mihai Postelnicu - mihai@code.ro
 */

/**
 * @author mihai type created by Mihai Postelnicu
 */
public class RSSNewActivitiesServlet extends HttpServlet {

    private int MAX_ACTIVITIES = 5;

    /*
     * (non-Javadoc)
     * 
     * @see ro.gateway.aida.struts.MultiTilesAction#modePrepare(org.apache.struts.action.ActionMapping,
     *      org.apache.struts.action.ActionForm,
     *      javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse)
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
		response.setContentType("text/xml");
        ServletContext application = this.getServletContext();
        PersistenceToken token = PersistenceManager.tokenLookup(application);
        
        String lang = request.getParameter("language");
        if (lang == null)
            lang = Constants.DEFAULT_LANGUAGE;
        ActivityDB adb = ActivityDB.getManager(token);
        OrganizationDB odb = OrganizationDB.getManager(token);        
        UserDB udb=UserDB.getManager(token);
        
        RSSFeedGenerator g = new RSSFeedGeneratorImpl();
        Channel cActivities = new Channel("Latest Projects", request.getRequestURL()
                .toString(),
                "Latest updated projects on Local Projects Database");
        Channel cOrgs= new Channel("Latest Organizations", request.getRequestURL()
                .toString(),
                "Latest updated organizations on Local Projects Database");
       
        
        //feed activities
        try {
            List activities = adb.getAllDataLatest(MAX_ACTIVITIES);

            Iterator i = activities.iterator();

            while (i.hasNext()) {
                Activity a = (Activity) i.next();
                String url = request.getRequestURL().toString().replaceFirst(
                        "latest.rss", "activity/view.jsp?id=" + a.getId());
                Item item = new Item(a.getTitle(lang), url, a
                        .getDescription(lang));
                item.setAuthor(udb.getById(a.getObject().getUser_id()).getFullName());
                item.setPubDate(new Date(a.getObject().getDate_modif()));
                Item.Guid ig=item.new Guid(url,true);
                ig.setPermaLink(true);
                item.setGuid(ig );
                
                for (int j = 0; j < a.getSectors().length; j++) {
                    item.getCategories().add(item.new Category(a.getSectors()[j].getSector().getTitle(lang)));                    
                }
                
                
                cActivities.addItem(item);

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        //feed orgs
        try {
            List orgs = odb.getAllDataLatest(MAX_ACTIVITIES);

            Iterator i = orgs.iterator();

            while (i.hasNext()) {
                Organization o = (Organization) i.next();
                String url = request.getRequestURL().toString().replaceFirst(
                        "latest.rss", "org/view?list=yes&id=" + o.getId());
                Item item = new Item(o.getName().getString(lang), url, o.getDescription().getString(lang));
                item.setAuthor(udb.getById(o.getUserID()).getFullName());
                item.setPubDate(o.getUpdate());
                Item.Guid ig=item.new Guid(url,true);
                ig.setPermaLink(true);
                item.setGuid(ig );
                
                item.getCategories().add( item.new Category(o.getType().getName().getString(lang)));
           
                
                cOrgs.addItem(item);

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        
        RSS rss = new RSS(RSS.VERSION_2_0);
        rss.addChannel(cActivities);
        rss.addChannel(cOrgs);

        String result = g.generateAsString(rss);

        PrintWriter out = response.getWriter();
        out.write(result);
        out.close();
    }

}